import sublime
import sublime_plugin
import urllib
#import requests

class GbOrGbkCommand(sublime_plugin.TextCommand):
	def run(self, edit , type = 'gb_to_gbk'):

		this_view = self.view
		this_select = this_view.sel()

		i = 0
		while i < len(this_select):
			sub_str = this_view.substr(this_select[i])
			re_str = gb_or_gbk(sub_str,type);
			if(re_str != False):
				this_view.replace(edit, this_select[i], re_str)
			i += 1

def gb_or_gbk(string,type):
	try:
		url = 'http://113.113.81.177:8010/gb_to_big_api.php'
		data = {'type' : type, 'data' : string}
		postdata=urllib.parse.urlencode(data).encode('utf-8')
		req=urllib.request.Request(url=url,data=postdata,method='POST')
		response=urllib.request.urlopen(req)
		html=response.read()
		return html.decode('utf-8')
	except Exception as e:
		sublime.error_message(str(e))
		return False